<template>
  <div>
    <el-steps class="step" :active="step">
      <el-step title="商品基本信息"></el-step>
      <el-step title="添加库存信息"></el-step>
      <el-step title="添加移动端详情"></el-step>
    </el-steps>
    <el-card shadow="never" class="card">
      <div slot="header">
        <div v-show="step === 1">
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="1">无忧退货</el-checkbox>
            <el-checkbox label="2">快速退款</el-checkbox>
            <el-checkbox label="3">免费包邮 </el-checkbox>
          </el-checkbox-group>
          <div>
            <p>基本信息</p>
            <div>
              商品编码：<el-input
                size="mini"
                style="width: 300px"
                v-model="homeInfo.productSn"
                placeholder="商品编码"
              ></el-input>
            </div>
            <div>
              商品品牌：<el-select
                v-model="homeInfo.brandName"
                size="mini"
                value-key="id"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in brandList"
                  :key="item.id"
                  :label="item.name"
                  :value="item"
                >
                </el-option>
              </el-select>
            </div>
            <div>
              商品分类：<el-select
                v-model="homeInfo.productCategoryName"
                size="mini"
                value-key="id"
                placeholder="请选择"
              >
                <el-option
                  v-for="item in addess"
                  :key="item.id"
                  :label="item.names"
                  :value="item"
                >
                </el-option>
              </el-select>
            </div>
            <div>
              商品描述：<el-input
                size="mini"
                style="width: 300px"
                v-model="homeInfo.description"
                placeholder="商品描述："
              ></el-input>
            </div>
          </div>
          <div>
            <p>商品属性</p>
            <div>
              商品原价
              <el-input-number
                size="mini"
                v-model="homeInfo.originalPrice"
                @change="handleChange"
                :min="1"
              ></el-input-number>
            </div>
            <div>
              重量(kg)
              <el-input-number
                size="mini"
                v-model="homeInfo.weight"
                @change="handleChange"
                :min="1"
              ></el-input-number>
            </div>
            <div>
              审核状态：<el-switch
                v-model="homeInfo.verifyStatus"
                active-color="#409EFF"
                inactive-color="#DCEFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>
            <div>
              是否上架：<el-switch
                v-model="homeInfo.publishStatus"
                active-color="#409EFF"
                inactive-color="#DCEFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>
            <div>
              <el-upload
                ref="upload"
                :action="uploadUrl"
                :headers="headers"
                :on-success="handleAvatarSuccess"
              >
                <el-button size="small" type="primary">缩略图</el-button>
              </el-upload>
              <img
                v-if="homeInfo.pic"
                :src="homeInfo.pic"
                style="height: 100px"
                alt=""
              />
            </div>
          </div>
          <div>
            <p>其他信息</p>
            <div>
              推荐状态：<el-switch
                v-model="homeInfo.recommendStatus"
                active-color="#409EFF"
                inactive-color="#DCEFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>
            <div>
              新品状态：<el-switch
                v-model="homeInfo.newStatus"
                active-color="#409EFF"
                inactive-color="#DCEFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>
            <div>
              预告商品：<el-switch
                v-model="homeInfo.previewStatus"
                active-color="#409EFF"
                inactive-color="#DCEFE6"
                :active-value="1"
                :inactive-value="0"
              >
              </el-switch>
            </div>
            <div>
              搜索关键词：<el-input
                size="mini"
                style="width: 300px"
                v-model="homeInfo.keywords"
                placeholder="关键词"
              ></el-input>
            </div>
            <div>
              库存预警
              <el-input-number
                size="mini"
                v-model="homeInfo.lowStock"
                @change="handleChange"
                :min="1"
              ></el-input-number>
            </div>
            <div>
              商品排序
              <el-input-number
                size="mini"
                v-model="homeInfo.sort"
                @change="handleChange"
                :min="1"
              ></el-input-number>
            </div>
          </div>
        </div>
        <div v-show="step === 2">
          <p>商品sku信息</p>
          <div>
            标题：<el-input
              size="mini"
              style="width: 300px"
              v-model="homeInfo.detailTitle"
              placeholder="标题"
            ></el-input>
          </div>
          <div>
            副标题：<el-input
              size="mini"
              style="width: 300px"
              v-model="homeInfo.detailDesc"
              placeholder="副标题"
            ></el-input>
          </div>
          <div>
            <el-upload
              ref="upload"
              :action="uploadUrl"
              :headers="headers"
              :on-success="handleAvatarSuccesser"
            >
              <el-button size="small" type="primary">画册图片</el-button>
            </el-upload>
            <img
              v-if="homeInfo.albumPics"
              :src="homeInfo.albumPics"
              style="height: 100px"
              alt=""
            />
          </div>
          <div v-show="colorObj.arr.length > 0">
            <span>颜色：</span>
            <!-- 绑定选中的数组 -->
            <el-checkbox-group v-model="colorObj.selectArr">
              <el-checkbox
                v-for="item in colorObj.arr"
                :key="item"
                :label="item"
              ></el-checkbox>
            </el-checkbox-group>
          </div>
          <div v-show="sizeObj.arr.length > 0">
            <span>大小：</span>
            <!-- 绑定选中的数组 -->
            <el-checkbox-group v-model="sizeObj.selectArr">
              <el-checkbox
                v-for="item in sizeObj.arr"
                :key="item"
                :label="item"
              ></el-checkbox>
            </el-checkbox-group>
          </div>
          <!-- 颜色输入框 -->
          <el-input
            v-model="colorObj.text"
            placeholder="颜色描述：比如土豪金"
            size="mini"
            style="display: inline-block; width: 100px; margin-right: 20px"
            clearable
          ></el-input>
          <el-button type="primary" size="mini" @click="createAttr('colorObj')"
            >创建颜色选项</el-button
          >
          <!-- 大小输入框 -->
          <el-input
            v-model="sizeObj.text"
            placeholder="大小"
            size="mini"
            style="display: inline-block; width: 100px; margin-right: 20px"
            clearable
          ></el-input>
          <el-button type="primary" size="mini" @click="createAttr('sizeObj')"
            >创建大小选项</el-button
          >
          <!-- 创建sku按钮 -->
          <div>
            <el-button type="primary" size="mini" @click="createSku"
              >新增sku</el-button
            >
          </div>
          <!-- skutable表单 -->
          <el-table v-if="skuTable.length > 0" :data="skuTable" border stripe>
            <el-table-column
              type="index"
              align="center"
              fixed="left"
              label="序号"
              width="50"
            ></el-table-column>
            <el-table-column prop="pic" label="图片" align="center" width="120">
              <template slot-scope="scope">
                <el-upload
                  class="avatar-uploader"
                  :action="uploadUrl"
                  :headers="headers"
                  :show-file-list="false"
                  :on-success="
                    res => {
                      myHandleAvatarSuccess(res, scope.row)
                    }
                  "
                >
                  <img
                    v-if="scope.row.pic"
                    :src="scope.row.pic"
                    class="avatar"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </template>
            </el-table-column>

            <el-table-column
              prop="color"
              align="center"
              label="颜色"
              width="100"
            ></el-table-column>
            <el-table-column
              prop="size"
              align="center"
              label="大小"
              width="100"
            ></el-table-column>
            <el-table-column label="操作" width="150" fixed="right">
              <template slot-scope="scope">
                <el-button
                  type="text"
                  style="color: red !important"
                  size="mini"
                  @click="del(scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div v-show="step === 3">
          <p>详情描述</p>
          <div>
            <p>商品详情</p>
            <Tin ref="Tin" />
          </div>
          <div>
            备注：<el-input
              size="mini"
              style="width: 300px"
              v-model="homeInfo.note"
              placeholder="备注"
            ></el-input>
          </div>
        </div>
        <div class="button-wrapper">
          <el-button type="primary" v-if="step > 1" size="mini" @click="step--"
            >上一页</el-button
          >
          <el-button type="primary" v-if="step < 3" size="mini" @click="step++"
            >下一页</el-button
          >
          <el-button
            type="primary"
            v-if="step === 3"
            size="mini"
            @click="submit"
            >提交保存</el-button
          >
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import product from '@/api/product.js'
import { v4 } from 'uuid'
import mixins from '@/mixins'
import Tin from '@/components/Tinymce/index.vue' //富文本
export default {
  mixins: [mixins],
  components: {
    Tin,
  },
  data() {
    return {
      checkList: [],
      skuTable: [], //sku
      step: 1,
      brandList: [],
      value: '', //下拉框选中对象
      colorObj: {
        //颜色
        text: '',
        arr: [], //生成的数组
        selectArr: [], //选中的数组
      },
      sizeObj: {
        //大小
        text: '',
        arr: [], //生成的数组
        selectArr: [], //选中的数组
      },
      pmsSkuStockList: [],
      homeInfo: {
        albumPics: '', //画册图片
        brandId: '', //商品id
        brandName: '', //商品品牌
        deleteStatus: '', //删除状态 0 删除 1未删除
        description: '', //商品描述
        detailDesc: '', //副标题
        detailTitle: '', //标题
        keywords: '', //关键词
        lowStock: '', //库存预警
        name: '', //商品名称
        newStatus: '', //新品状态  0不是新品 1 新品
        note: '', //备注
        originalPrice: '', //商品原价
        pic: '', //缩略图
        previewStatus: '', //是否为预告商品  0 是 1 不是
        price: '', //活动价格
        productAttributeCategoryId: '', //产品属性分类
        productCategoryId: '',
        productCategoryName: '', //商品分类
        productSn: '', //商品编码
        promotionType: '', //促销类型：0->没有促销使用原价;1->使用促销价；2->使用会员价；3->使用阶梯价格；4->使用满减价格；5->限时购 ,
        publishStatus: '', //上架状态：0->下架；1->上架 ,
        recommendStatus: '', //推荐状态 0 推荐 1 不推荐
        serviceIds: '', // 以逗号分割的产品服务：1->无忧退货；2->快速退款；3->免费包邮 ,
        sort: '', //商品排序
        verifyStatus: '', //审核状态  0审核 1未审核
        weight: '', //重量
      },
      addess: {
        0: {
          names: '创意',
        },
        1: {
          names: '风格',
        },
        2: {
          names: '饰品',
        },
        3: {
          names: '灯具',
        },
      },
    }
  },
  mounted() {},
  created() {
    product.findAllBrandApi().then(res => {
      this.brandList = res.data.items
      console.log(this.brandList, 'aaa')
    })
  },
  methods: {
    //上传成功
    myHandleAvatarSuccess(res, row) {
      console.log(res, 'res')
      console.log(row, 'row')
      if (res.success) {
        row.pic = res.data.fileUrl
      } else {
        this.$message('发生未知错误，上传图片失败')
      }
    },
    //提交
    submit() {
      console.log('提交', this.checkList.join(','), 'checkList')

      this.skuTable.forEach(item => {
        delete item.tempId
      })
      product
        .addProductAndSkusApi({
          pmsSkuStockList: [],
          product: this.homeInfo,
          // albumPics: this.homeInfo.albumPics,
          // brandId: this.homeInfo.brandId,
          // brandName: this.homeInfo.brandName,
          // deleteStatus: this.homeInfo.deleteStatus,
          // description: this.homeInfo.description,
          // detailDesc: this.homeInfo.detailDesc,
          // detailTitle: this.homeInfo.detailTitle,
          // keywords: this.homeInfo.keywords,
          // lowStock: this.homeInfo.lowStock,
          // name: this.homeInfo.name,
          // newStatus: this.homeInfo.newStatus,
          // note: this.homeInfo.note,
          // originalPrice: this.homeInfo.originalPrice,
          // pic: this.homeInfo.pic,
          // previewStatus: this.homeInfo.previewStatus,
          // price: this.homeInfo.price,
          // productAttributeCategoryId:
          //   this.homeInfo.productAttributeCategoryId,
          // productCategoryId: this.homeInfo.productCategoryId,
          // productCategoryName: this.homeInfo.productCategoryName,
          // productSn: this.homeInfo.productSn,
          // promotionType: this.homeInfo.promotionType,
          // publishStatus: this.homeInfo.publishStatus,
          // recommendStatus: this.homeInfo.recommendStatus,
          // serviceIds: this.homeInfo.serviceIds,
          // sort: this.homeInfo.sort,
          // verifyStatus: this.homeInfo.verifyStatus,
          // weight: this.homeInfo.weight,
        })
        .then(res => {
          console.log(res, 'res!!!')
        })
      this.$router.push({ name: 'productList' })
    },
    createAttr(attr) {
      this[attr].arr.push(this[attr].text)
      this[attr].text = ''
      console.log(this[attr])
    },
    createSku() {
      var arr = [
        this.colorObj.selectArr,
        this.sizeObj.selectArr,
        // ['pro', 'mini'],
      ]
      var skuList = arr.reduce((total, current) => {
        var newArr = []
        //先循环外层（上一级抛出来的数组）数组
        total.forEach(out => {
          //再循环当前数组
          current.forEach(inner => {
            if (typeof out === 'object') {
              //如果是数组的话 应该用...解构出来
              newArr.push([...out, inner])
            } else {
              newArr.push([out, inner])
            }
          })
        })
        return newArr
      })
      console.log(skuList, 'skuList')
      //生成skutable数据
      skuList.forEach(item => {
        var obj = {
          lowStock: 0,
          pic: '',
          price: 0,
          skuCode: '',
          stock: 0,
          color: item[0], //颜色
          size: item[1], //大小
          tempId: v4(),
        }
        this.skuTable.push(Object.assign({}, obj))
      })
    },
    //删除
    del(row) {
      console.log(row, '删除')
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        //过滤掉不等于当前删除的tempId的数据
        this.skuTable = this.skuTable.filter(item => item.tempId !== row.tempId)
      })
    },
    handleChange(value) {
      console.log(value)
    },
    handleAvatarSuccess(res) {
      console.log(res, 'resss')
      if (res.success) {
        this.homeInfo.pic = res.data.fileUrl
        // this.$refs.upload.clearFiles()
      } else {
        this.$message.error('上传失败')
      }
    },
    handleAvatarSuccesser(res) {
      console.log(res, 'resss')
      if (res.success) {
        this.homeInfo.albumPics = res.data.fileUrl
        // this.$refs.upload.clearFiles()
      } else {
        this.$message.error('上传失败')
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.step {
  margin: 30px;
}
.card {
  margin: 30px;
}
.button-wrapper {
  width: fit-content;
  margin: 10px auto;
  position: absolute;
  bottom: 50px;
  left: 800px;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
.avatar-uploader {
  width: 100px;
  height: 100px;
}
.el-upload {
  width: 100px;
  height: 100px;
}
</style>
